<?php


/**
 * Presenter pro upravu stranek.
 *
 * @author David Dusek
 */

use Nette\Application\UI\Form,
    CMS\Page\Models\Page;

class PagePresenter extends AdminPresenter
{
    public function renderDefault() {
        $this->isAllowed("list", TRUE);
        $this->template->title = $this->getTitle("title", "list");
    }
    
    public function renderAdd() {
        $this->isAllowed("add", TRUE);
        $this->template->title = $this->getTitle("title", "add");
    }
    
    public function renderEdit($id) {
        $this->isAllowed("edit", TRUE);
        $this->template->title = $this->getTitle("title", "edit");
    }
    
    protected function createComponentGrid() {
        $grid = new \Gridito\Grid($this, 'grid');
        $presenter = $this;
       
        $qb = $this->em->getRepository('\CMS\Page\Models\Page')->createQueryBuilder('p');        
        $grid->setModel(new CMS\DoctrineQueryBuilderModel($qb));
        $grid->addColumn('id', 'Id');
        $grid->addColumn('name', $this->translate('name'))->setSortable(true);
        $grid->addColumn('title', $this->translate('pageTitle'))->setSortable(true);
        $grid->addColumn('layout', $this->translate('layout'))->setSortable(true);
        $grid->addColumn('content.address', $this->translate('address'))->setSortable(true);
        $grid->addColumn('content.homepage', $this->translate('homepage'), array(
                'renderer' => function ($page) use ($presenter) {
                        $status = $page->content->homepage ? "on" : "off";
                        $imgSrc = "/CMS/images/status_$status.png";                    
                        $link = \Nette\Utils\Html::el("a")->addAttributes(
                                array(
                                    "class" => "ajax",
                                    "href" => $presenter->link("setHomepage!", $page->content->id),
                                ));                    

                        $img = \Nette\Utils\Html::el("img")->addAttributes(
                                array(
                                    "src" => $imgSrc, 
                                    "alt" => $status,
                                    "width" => "24px",
                                    "height" => "24px"
                                ));
                        $link->add($img);
                        echo $link;
                    }
            ));
        $grid->addColumn('content.active', $this->translate('active'), array(
                'renderer' => function ($page) use ($presenter) {
                    $status = $page->content->active ? "on" : "off";
                    $imgSrc = "/CMS/images/status_$status.png";                    
                        $link = \Nette\Utils\Html::el("a")->addAttributes(
                                array(
                                    "class" => "ajax",
                                    "href" => $presenter->link("toggleActive!", $page->content->id),
                                ));                    

                        $img = \Nette\Utils\Html::el("img")->addAttributes(
                                array(
                                    "src" => $imgSrc, 
                                    "alt" => $status,
                                    "width" => "24px",
                                    "height" => "24px"
                                ));
                        $link->add($img);
                        echo $link;
                    }
            ));
                
        if ($this->isAllowed("edit")) { 
            $grid->addButton('editButton', $this->translate('edit'), array(
                            'icon' => 'ui-icon-pencil',
                            'handler' => function ($page) use ($presenter) {
                                $presenter->redirect(':Page:Page:edit', array("id" => $page->id));
                            },
                    ))
                    ->setShowText(false);
        }
              
        
        if ($this->isAllowed("delete")) {
            $em = $this->em;
            $delMsg = $this->translate("deleteSucceeded");
            $grid->addButton('deleteButton', $this->translate('delete'), array(
                            'icon' => 'ui-icon-trash',
                            'handler' => function ($page) use ($grid, $delMsg, $em) {
                                $em->remove($page);
                                $em->flush();
                                $grid->flashMessage(vsprintf($delMsg, array($page->name)));
                            },
                    ))
                    ->setConfirmationQuestion($this->translate('deleteConfirnQuestion'))
                    ->setShowText(false)
                    ->setAjax(true);
        }
    }
    
    protected function createComponentLogComp() {
        $id = $this->getParameter("id");        
        $params = array("logComp", $this, "Page", $id);
        $log = $this->core->runHook("hookUserGetLogComponent", $params, "UserModule");
        return $log;
    }
    
    /**
     * Handler pro nastaveni stranky jako domovske.
     * @param int $id Id contentu.
     */
    public function handleSetHomepage($id) {
        $cr = $this->em->getRepository("\CMS\Page\Models\Content");
        $pr = $this->em->getRepository("\CMS\Page\Models\Page");
        $content = $cr->find($id);
        if ($content !== NULL) {    
            $content->active = TRUE;
            $this->core->runHook("hookPageSetLikeHomepage", $content, "PageModule");
            
            // zalogovani
            $page = $pr->findOneByContent($id);
            if ($page !== NULL) {
                 $this->addPageToLog($page, "logLikeHomepage");
            }
        }
        $this->invalidateControl("gridWrapper");
    }
    
    /**
     * Handler pro prepnuti publikace modulu.
     * @param int $id Id contentu.
     */
    public function handleToggleActive($id) {
        $content = $this->em->getRepository("\CMS\Page\Models\Content")->find($id);
        if ($content !== NULL) {         
            $content->active = !$content->active;
            
            // zalogovani
            $pr = $this->em->getRepository("\CMS\Page\Models\Page");
            $page = $pr->findOneByContent($id);
            if ($page !== NULL) {
                 $this->addPageToLog($page, $content->active ? "logPublishPage" : "logHidePage");
            }
            
            $this->em->flush();
        }
        
        $this->invalidateControl("gridWrapper");
    }
    
    /**
     * Formular pro pridani a editaci stranky.
     * @return \Nette\Application\UI\Form 
     */
    protected function createComponentPageForm() {
        $form = new Form();
        $action = $this->getAction();
        
        $layoutsOptions = $this->core->runHook("hookGetLayouts", TRUE, 'ConfigModule');        
               
        $form->addText("name", $this->translate("name"))->setRequired($this->translate("errRequired"));
        $form->addText("title", $this->translate("pageTitle"));
        $form->addSelect("layout", $this->translate('layout'), $layoutsOptions);
        $form->addText("address", $this->translate('address'));
        $form->addTextArea("keywords", $this->translate("keywords"), 40, 5);
        $form->addTextArea("description", $this->translate("description"), 40, 5);
        $form->addTextArea("content", $this->translate("content"))->getControlPrototype()->class("mark-it-up");        
        
        if ($action == "add") {
            $form->addSubmit("add", $this->translate('add'));
        } else {                    
            $form->addSubmit("edit", $this->translate('edit'));
            $id = intval($this->getParameter("id"));
            
            if ($id > 0) {
                $pageRepository = $this->em->getRepository("\CMS\Page\Models\Page");
                $page = $pageRepository->find($id);
                
                if ($page === null) {
                    $this->flashMessage($this->translate("editWrongId"));
                    $this->redirect(":Page:Page:default");
                }
                
                $form->addHidden("id")->setDefaultValue($page->id);                

                $form->setDefaults(array(
                    "name" => $page->name,
                    "title" => $page->title,
                    "keywords" => $page->keywords,
                    "description" => $page->description,
                    "content" => $page->contentText,
                    "layout" => $page->layout,
                    "address" => $page->content->address,
                    "homepage" => $page->content->homepage,
                    "active" => $page->content->active
                ));
            }
        }
        $form->onSuccess[] = callback($this, 'pageFormSubmitted');
        
        return $form;
    }
    
    /**
     * Zpracovani odeslaneho formulare pro editaci nebo pridani stranky.
     * @param Form $form 
     */
    public function pageFormSubmitted(Form $form) {
        $values = $form->getValues();
        $action = $this->getAction();
        
        if (!isset($values["address"]) || empty($values["address"])) {
            $address = \Nette\Utils\Strings::webalize($values["name"], "/");
        } else {
            $address = \Nette\Utils\Strings::webalize($values["address"], "/");
        }
        
        $pageId = isset($values["id"]) ? $values["id"] : FALSE;
        if ($pageId) {
            $pageRepository = $this->em->getRepository("\CMS\Page\Models\Page");
            $page = $pageRepository->find($pageId);
            $contentId = $page->content->id;
        } else {
            $page = new Page();
            $contentId = FALSE;
        }
        
        if (!$this->core->runHook("hookIsAddressAvailable", array($address, $contentId), "PageModule")) {
            $form->addError(vsprintf($this->translate("errAddressExist"), array($address)));
        } else {
            $action = $this->getAction();

            if ($action == "add") {
                $this->flashMessage($this->translate("addPageSucceeded"));
            } else {;
                $this->flashMessage($this->translate("editPageSucceeded"));
            }

            $page = $this->setPageData($page, $values);
            $this->em->persist($page);
            $this->em->flush();

            $contentData = $values;
            $contentData["module"] = "PageModule";
            $contentData["contentId"] = $page->id;
            $contentData["editedContentId"] = $page->content->id;
            $contentData["address"] = $address;
            $content = $this->core->runHook("hookAddContent", array($values), "PageModule");

            if ($content !== FALSE) {
                $page->setContent($content);
                $this->em->persist($page);
                $this->em->flush();
            }

            // zalogovani
            $this->addPageToLog($page, $action == "add" ? "logAddPage" : "logEditPage");
            
            $this->redirect(":Page:Page:edit", array("id" => $page->id));        
        }
    }
    
    /**
     * Pridani informace o zmene stranky do logu.
     * @param \CMS\Page\Models\Page $page
     * @param string $action Index do prekladoveho slovniku bez prefixu modulu.
     */
    private function addPageToLog($page, $action) {
        $link = $this->link(":Page:Page:edit", array("id" => $page->id));
        
        switch ($action) {
            case "logAddPage":
            case "logEditPage":
                $descData = array();
                $descData["name"] = $page->name;
                $descData["title"] = $page->title;
                $descData["layout"] = $page->layout;
                $descData["address"] = $page->getContent()->address;
                $descData["keywords"] = $page->keywords;
                $descData["description"] = $page->description;
                $descData["content"] = $page->contentText;
                $this->addToLog("Page", $page->id, $link, $action, $descData);
                break;
            case "logLikeHomepage":
            case "logPublishPage":
            case "logHidePage":
                $this->addToLog("Page", $page->id, $link, $action);
                break;
        }
        
        
    }
    
    /**
     * Nastaveni hodnot objektu tridz Page.
     * @param \CMS\Page\Models\Page $page
     * @param array $values Hodnoty z formulare.
     * @return \CMS\Page\Models\Page 
     */
    private function setPageData(Page $page, $values) {
        $page->setName($values["name"]);
        $page->setTitle($values["title"]);
        $page->setKeywords($values["keywords"]);
        $page->setDescription($values["description"]);
        $page->setContentText($values["content"]);
        $page->setLayout($values["layout"]);
        
        return $page;
    }
}
